package com.lily.aidouzixun.util;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.util.ArrayMap;

import com.lily.aidouzixun.fragment.UserCenterFragment;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 数据转换工具类
 */
public class DataConverter {
    private static final String TAG = "DataConverter";

    /**
     * String -> Int
     * @param strInt
     * @return null or empty return 0
     */
    public static int parseInt(String strInt) {
        return parseInt(strInt, 0);
    }

    /**
     * String -> Int
     * @param strInt
     * @param defaultValue 当要转换的字符串不是数字时，默认返回数值
     * @return
     */
    public static int parseInt(String strInt, int defaultValue) {
        if(strInt == null || "".equals(strInt)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(strInt);
        } catch (Exception e) {
            return defaultValue;
        }
    }
    /**
     *得到 md5
     * @param source
     * @return 32 characters which represent a 128 bits long integer
     */
    public static String getMD5(byte[] source) {
        String s = "";
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            s = convertMD5(md.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public static String convertMD5(byte[] byteMD5) {
        // 用来将字节转换成 16 进制表示的字符
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符， 所以表示成 16 进制需要
        // 32 个字符
        int k = 0; // 表示转换结果中对应的字符位置
        for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节 转换成 16 进制字符的转换
            byte byte0 = byteMD5[i]; // 取第 i 个字节
            str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, // >>>
            // 为逻辑右移，将符号位一起右移
            str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
        }
        return new String(str); // 换后的结果转换为字符串
    }

    /**
     * 通过map生成请求参数
     * @return
     */
    public static String createParamByMap(ArrayMap<String, String> params) {
        StringBuffer result = new StringBuffer();
        Set paramSet = params.entrySet();
        Iterator iterator = paramSet.iterator();
        while (iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry)iterator.next();
            result.append(mapEntry.getKey() + "=" + mapEntry.getValue() + "&");
        }
        return result.substring(0, result.length() - 1);
    }

    /**
     * 根据图片路径得到Bitmap对象
     * @param path
     * @return
     */
    public static Bitmap getBitmapFormFilePath(String path, int height, int width) {
        try {
            //先解析图片边框的大小
            BitmapFactory.Options ops = new BitmapFactory.Options();
            ops.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(path, ops);
            ops.inSampleSize = 1;
            int oHeight = ops.outHeight;
            int oWidth = ops.outWidth;
            //控制压缩比
            int contentHeight = height;
            int contentWidth = width;

            if (((float)oHeight / contentHeight) < ((float)oWidth / contentWidth)) {
                ops.inSampleSize = (int) Math.ceil((float)oWidth / contentWidth);
            } else {
                ops.inSampleSize = (int) Math.ceil((float)oHeight / contentHeight);
            }
            ops.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(path, ops);
            return bitmap;
        } catch (Exception e) {
            L.e(TAG, "getBitmapFormFilePath error!");
            return null;
        }
    }

    /**
     * 根据Uri得到真实路径
     * @param uri
     * @return
     */
    public static String getRealPathFromURI(Context context, Uri uri) {
        try {
            String res = null;
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(columnIndex);
            }
            cursor.close();
            return res;
        } catch (Exception e) {
            L.e(TAG, "getRealPathFromURI error");
            return null;
        }
    }

    /**
     * 根据uri得到照片地址，这是目前可用的方法
     *
     * @param context
     * @param avatarUri
     * @return
     */
    public static String getFilePathByUri(Context context, Uri avatarUri) {
        String avatarPath = "";
        if (avatarUri.toString().startsWith("file")) { // file://
            avatarPath = avatarUri.toString().substring(6);
        } else if (Build.VERSION.SDK_INT >= 19) {
            avatarPath = getPath(context, avatarUri);
        } else if (avatarUri.toString().startsWith("content")) {
            Cursor cursor = context.getContentResolver().query(avatarUri, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                // String imgNo = cursor.getString(0); //图片编号
                avatarPath = cursor.getString(1); // 图片文件路径
                // String imgSize = cursor.getString(2); //图片大小
                // String imgName = cursor.getString(3); //图片文件名
                cursor.close();
            }
        } else {
            return null;
        }
        return avatarPath;
    }
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= 19;

        boolean isDocumentUri = false;
        String documentId = "";
        isDocumentUri = invokeIsDocumentUri(context, uri);
        documentId = invokeGetDocumentId(uri);
        // DocumentProvider
        if (isKitKat && isDocumentUri) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = documentId;
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = documentId;
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = documentId;
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
    private static boolean invokeIsDocumentUri(Context context, Uri uri) {
        try {
            Class<?> ownerClass = Class.forName("android.provider.DocumentsContract");
            Method method = ownerClass.getMethod("isDocumentUri", android.content.Context.class, android.net.Uri.class);
            return (Boolean) (method.invoke(null, context, uri));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }

    private static String invokeGetDocumentId(Uri uri) {
        try {
            Class<?> ownerClass = Class.forName("android.provider.DocumentsContract");
            Method method = ownerClass.getMethod("getDocumentId", android.net.Uri.class);
            return (String) (method.invoke(null, uri));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    /**
     * 根据Bitmap生成文件路径
     * @param bm
     * @param path
     * @throws IOException
     */
    public static void getFilePathByBitmap(final Bitmap bm, final String path, final int action){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = new File(path);
                    if(file.exists()){
                        file.delete();
                    }
                    FileOutputStream out;
                    try{
                        out = new FileOutputStream(file);
                        if(bm.compress(Bitmap.CompressFormat.PNG, 90, out))
                        {
                            out.flush();
                            out.close();
                        }
                    }
                    catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.SAVE_AVATAR_FINISHED, action);
            }
        }).start();
    }

    /**
     * 得到当前时间
     * @return eg:2015-08-06 18:56:01
     */
    public static String getCurDayTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = new Date();
        String dayTime = formatter.format(currentTime);
        return dayTime;
    }


}
